package com.chagee.store.operation.server.config;

import com.chagee.store.operation.server.utils.SerializeUtil;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author yinhao
 * @date 2018/6/5 19:35
 */
@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String ip;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;
	@Value("${spring.redis.database}")
	private String database;

	@Bean
	public RedissonClient singleRedissonLock() {
		Config config = new Config();
		config.useSingleServer()
			.setAddress("redis://" + ip + ":" + port)
			.setPassword(StringUtils.defaultIfEmpty(password, null));
		return Redisson.create(config);
	}

	@Bean(name = "redisConnectionFactory")
	public RedisConnectionFactory initConnectionFactory() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(200);
		jedisPoolConfig.setMaxIdle(150);
		jedisPoolConfig.setMinIdle(50);
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setHostName(ip);
		redisStandaloneConfiguration.setPort(Integer.parseInt(port));
		redisStandaloneConfiguration.setPassword(password);
		redisStandaloneConfiguration.setDatabase(Integer.parseInt(database));
		JedisClientConfiguration.JedisClientConfigurationBuilder configurationBuilder = JedisClientConfiguration.builder();
		JedisClientConfiguration jedisClientConfiguration = configurationBuilder.usePooling().poolConfig(jedisPoolConfig).build();
		return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
	}

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redis = new RedisTemplate<>();
		redis.setConnectionFactory(redisConnectionFactory);
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		SerializeUtil serializeUtil = new SerializeUtil();
		redis.setKeySerializer(stringRedisSerializer);
		redis.setValueSerializer(serializeUtil);
		redis.afterPropertiesSet();
		return redis;
	}
}
